/*
 * Copyright (c) 2015, the Dart project authors.
 *
 * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package vm.element

// This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk.

import com.google.gson.JsonArray
import com.google.gson.JsonObject

class CpuSamplesEvent(json: JsonObject) : Element(json) {

    /**
     * A list of references to functions seen in the relevant samples. These references can be looked
     * up using the indices provided in a `CpuSample` `stack` to determine which function was on the
     * stack.
     *
     * @return one of <code>ElementList<ObjRef></code> or <code>ElementList<NativeFunction></code>
     */
    fun getFunctions(): Any? {
        val elem = json.get("functions") ?: return null

        if (elem.isJsonObject) {
            val o = elem.asJsonObject
            when (o.get("type")?.asString) {
                "@Obj" -> return ObjRef(o)
                "NativeFunction" -> return NativeFunction(o)
            }
        }
        return null
    }

    /**
     * The maximum possible stack depth for samples.
     */
    fun getMaxStackDepth(): Int {
        return getAsInt("maxStackDepth")
    }

    /**
     * The process ID for the VM.
     */
    fun getPid(): Int {
        return getAsInt("pid")
    }

    /**
     * The number of samples returned.
     */
    fun getSampleCount(): Int {
        return getAsInt("sampleCount")
    }

    /**
     * The sampling rate for the profiler in microseconds.
     */
    fun getSamplePeriod(): Int {
        return getAsInt("samplePeriod")
    }

    /**
     * A list of samples collected in the range `[timeOriginMicros, timeOriginMicros +
     * timeExtentMicros]`
     */
    fun getSamples(): ElementList<CpuSample> {
        return object : ElementList<CpuSample>(json.get("samples").asJsonArray) {
            override fun basicGet(array: JsonArray, index: Int): CpuSample {
                return CpuSample(array.get(index).asJsonObject)
            }
        }
    }

    /**
     * The duration of time covered by the returned samples.
     */
    fun getTimeExtentMicros(): Int {
        return getAsInt("timeExtentMicros")
    }

    /**
     * The start of the period of time in which the returned samples were collected.
     */
    fun getTimeOriginMicros(): Int {
        return getAsInt("timeOriginMicros")
    }
}
